package com.ymh.git.thread.juc;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

/**
 * Created by aivin on 2018/10/31.
 */
public class FindDirsFiles extends RecursiveAction {

    private File path;//统计的目录

    public FindDirsFiles(File path) {
        this.path = path;
    }

    @Override
    protected void compute() {

        List<FindDirsFiles> subTasks = new ArrayList<>(); //子目录任务的容器

        File[] files = path.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    subTasks.add(new FindDirsFiles(file));
                } else {
                    //遇到文件的时候，进行检查，判断文件类型符合要求与否
                    if (file.getAbsolutePath().endsWith("txt")) {
                        System.out.println("文件：" + file.getAbsolutePath());
                    }
                }
            }
        }

        if (!subTasks.isEmpty()) {
            for (FindDirsFiles subtask : invokeAll(subTasks)) {
                subtask.join();
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        FindDirsFiles totalTask = new FindDirsFiles(new File("/Users/aivin/Downloads/"));
        forkJoinPool.execute(totalTask); //异步执行

        Thread.sleep(5);
        System.out.println("I am OK");

        totalTask.join();
        System.out.println("Task end");
    }
}
